//定义js命名空间
Ext.namespace('FsCarInfo.FsCartransfer');
//TODO : 完善数据结构
//DateTime -- date , decimal -- float
// { name: 'Department.Name', mapping: 'Department.Name' },
// { name: 'Department'},
//FsCartransfer FieldArray
FsCarInfo.FsCartransfer.BaseFieldsArray = new Array(
	{ name: 'Id', type: 'string' },
	{ name: 'TransferType', type: 'int' },
	{ name: 'OperUserId', type: 'string' },
	{ name: 'OperUser.Name', mapping: 'OperUser.Name' },
	{ name: 'OutDeptId', type: 'string' },
	{ name: 'OutDept.Name', mapping: 'OutDept.Name' },
	{ name: 'OutDpuserId', type: 'string' },
	{ name: 'OutDpuser.Name', mapping: 'OutDpuser.Name' },
	{ name: 'InDeptId', type: 'string' },
	{ name: 'InDept.Name', mapping: 'InDept.Name' },
	{ name: 'InDpuserId', type: 'string' },
	{ name: 'InDpuser.Name', mapping: 'InDpuser.Name' },
	{ name: 'ExpOutTime', type: 'date' },
	{ name: 'ExpArvTime', type: 'date' },
	{ name: 'ActOutTime', type: 'string' },
	{ name: 'ActArvTime', type: 'string' },
	{ name: 'Reason', type: 'string' },
	{ name: 'Description', type: 'string' },
	{ name: 'State', type: 'int' },
	{ name: 'IsDelete', type: 'bool' },
	{ name: 'Version', type: 'int' },
	{ name: 'CreateUser', type: 'string' },
	{ name: 'CreateTime', type: 'date' }
);

//FsCartransfer JsonReader
FsCarInfo.FsCartransfer.JsonReader = Ext.extend(Infrastructure.BaseJsonReader, {
	constructor: function (cfg) {
		cfg = cfg || {};
		FsCarInfo.FsCartransfer.JsonReader.superclass.constructor.call(this, Ext.apply({
			fields: FsCarInfo.FsCartransfer.BaseFieldsArray
		}, cfg));
	}
});

//FsCartransfer JsonStore
FsCarInfo.FsCartransfer.JsonStore = Ext.extend(Infrastructure.BaseJsonStore, {
	constructor: function (cfg) {
		cfg = cfg || {};
		FsCarInfo.FsCartransfer.JsonStore.superclass.constructor.call(this, Ext.apply({
			url: '/FsCartransfer/GetPlist',
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING
			},
			remoteSort: true,
			fields: FsCarInfo.FsCartransfer.BaseFieldsArray,
			listeners: {
				'remove': function (thiz, record, index) {
					Ext.Ajax.request({
						url: '/FsCartransfer/Delete?Id=' + record.data.Id,
						success: function (response, opts) {
							var result = Ext.util.JSON.decode(response.responseText);
							if (result.success == false) {
								JsHelper.ShowError(result.msg);
								this.insert(0, record);
							}
						}
					});
				}
			}
		}, cfg));
	}
});

//FsCartransfer GridPanel
FsCarInfo.FsCartransfer.GridPanel = Ext.extend(Infrastructure.BaseGridPanel, {
	// User property
	//基本处理Url
	baseUrl: '/FsCartransfer/',
	//提交保存Url
	formSubmitUrl: '/FsCartransfer/SaveOrUpdate',
	//审批处理Url
	approveUrl: '/FsCartransfer/Approve',
	//提交保存提示信息
	formSubmitMsg: '确定要保存吗?',
	//工具栏标签
	tbarMask: '0',
	//表格列默认显示
	columnMask: '112345678911234567890123000000',
	//状态
	itemState: '',
	//调拨类型
	transferType: '',

	store: new FsCarInfo.FsCartransfer.JsonStore(),

	//initComponent
	initComponent: function () {
		//prepare

		var itemGrid = this;
		var colMask = this.columnMask;
		var cmdAddEntity = this.onAddEntity;
		var cmdDeleteEntity = this.onDeleteEntity;
		var cmdLoadEntity = this.onLoadEntity;
		var cmdQueryList = this.onToApproveEntity;
		//提交审批
		var cmdToApproveEntity = function () {
			this.tbarSubmit(this.baseUrl + 'ToApproveProcess', '确定要将商品车调派单提交审批吗?', '您的调派单已提交审批,请等待..');
		};
		//出库
		var cmdSendOut = function () {
			this.tbarSubmit(this.baseUrl + 'SendOut', '确定要提车出库吗?', '调派单已提出.');
		};
		//接收
		var cmdSendRecive = function () {
			this.tbarSubmit(this.baseUrl + 'SendRecive', '该调派单车辆已全部抵达仓库?确定要接收?', '调派单已接收,可以进行复核入库.');
		};
		//复核入库
		var cmdSendStoreIn = function () {
			this.tbarSubmit(this.baseUrl + 'SendStoreIn', '复核无误,调派单可以入库?', '调派单及商品车信息已复核入库.');
		};
		//set store params
		this.store.setBaseParam('state', this.itemState);
		this.store.setBaseParam('type', this.transferType);

		// The filter.
		var gridFilter = new Ext.ux.grid.GridFilters({
			encode: true,
			filters: [
				{ dataIndex: 'Id', type: 'string' },
				{ dataIndex: 'TransferType', type: 'list', options: JsHelper.GetFilterListData(FsCarInfo.Params.CarTransfer_TypeStore.data.items, 'Code', 'Name') },
				{ dataIndex: 'OperUser', type: 'string' },
				{ dataIndex: 'OutDept.Name', type: 'string' },
				{ dataIndex: 'OutDpuser.Name', type: 'string' },
				{ dataIndex: 'InDept.Name', type: 'string' },
				{ dataIndex: 'InDpuser.Name', type: 'string' },
				{ dataIndex: 'ExpOutTime', type: 'string' },
				{ dataIndex: 'ExpArvTime', type: 'string' },
				{ dataIndex: 'ActOutTime', type: 'string' },
				{ dataIndex: 'ActArvTime', type: 'string' },
				{ dataIndex: 'Reason', type: 'string' },
				{ dataIndex: 'Description', type: 'string' },
				{ dataIndex: 'State', type: 'list', options: JsHelper.GetFilterListData(FsCarInfo.Params.CarTransfer_StateStore.data.items, 'Code', 'Name') },
				{ dataIndex: 'IsDelete', type: 'string' },
				{ dataIndex: 'Version', type: 'string' },
				{ dataIndex: 'CreateUser', type: 'string' },
				{ dataIndex: 'CreateTime', type: 'string' }
			]
		});

		// selModel
		var selModel = new Ext.grid.CheckboxSelectionModel({
			//header: '',
			//singleSelect: true,
			listeners: {
				'selectionchange': function (sm) {
					// 控制工具栏按钮是否可用
					itemGrid.delBtn.setDisabled(sm.getCount() < 1);
					itemGrid.btnToApprove.setDisabled(sm.getCount() < 1);
					itemGrid.btnSendOut.setDisabled(sm.getCount() != 1);
					itemGrid.btnSendRecive.setDisabled(sm.getCount() != 1);
					itemGrid.btnSendStoreIn.setDisabled(sm.getCount() != 1);
					// 根据状态控制
					var s = itemGrid.getSelectionModel().getSelections();
					/*
					for (var i = 0, r; r = s[i]; i++) {
						if (r.data.State != '待提交') {
							itemGrid.delBtn.setDisabled(true);
							itemGrid.btnToApprove.setDisabled(true);
						}
						if (r.data.State != '已审批') {
							itemGrid.btnSendOut.setDisabled(true);
						}
						if (r.data.State != '已提出') {
							itemGrid.btnSendRecive.setDisabled(true);
						}
						if (r.data.State != '已抵达') {
							itemGrid.btnSendStoreIn.setDisabled(true);
						}
					}
					*/
				}
			}
		});

		var approveColumn = new Infrastructure.InfraApproveLog.ApproveColumn({
			width: 25,
			approveUrl: this.approveUrl,
			appDisable: this.columnMask.charAt(0) == '0'
		});

		// columnModel 对于不常需要显示的 hidden: true 
		var gridColumn = new Ext.grid.ColumnModel({
			columns: [
				new Ext.grid.RowNumberer(),
				selModel,
				approveColumn,
			//{ header: "类型", dataIndex: 'TransferType', hidden: this.columnMask.charAt(1) == '0' },
				{header: "经办", dataIndex: 'OperUser.Name', hidden: this.columnMask.charAt(2) == '0' },
				{ header: "调出仓", dataIndex: 'OutDept.Name', hidden: this.columnMask.charAt(3) == '0' },
				{ header: "调出", dataIndex: 'OutDpuser.Name', hidden: this.columnMask.charAt(4) == '0' },
				{ header: "调入仓", dataIndex: 'InDept.Name', hidden: this.columnMask.charAt(5) == '0' },
				{ header: "调入", dataIndex: 'InDpuser.Name', hidden: this.columnMask.charAt(6) == '0' },
				{ header: "预计出发", dataIndex: 'ExpOutTime', xtype: 'datecolumn', format: 'Y-m-d H:i', hidden: this.columnMask.charAt(7) == '0' },
				{ header: "预计到达", dataIndex: 'ExpArvTime', xtype: 'datecolumn', format: 'Y-m-d H:i', hidden: this.columnMask.charAt(8) == '0' },
				{ header: "实际出发", dataIndex: 'ActOutTime', hidden: this.columnMask.charAt(9) == '0' },
				{ header: "实际到达", dataIndex: 'ActArvTime', hidden: this.columnMask.charAt(10) == '0' },
				{ header: "事由", dataIndex: 'Reason', hidden: this.columnMask.charAt(11) == '0' },
				{ header: "状态", dataIndex: 'State', hidden: this.columnMask.charAt(12) == '0' }
			],
			defaults: { sortable: true }
		});

		// PageBar
		var pagebBar = new Infrastructure.BasePagingToolbar({
			store: this.store,
			plugins: this.plugins
		});

		// 常用工具栏
		var toolBar = ['-', {
			xtype: 'tbaraddbtn',
			hidden: this.tbarMask.charAt(0) != '1',
			handler: cmdAddEntity,
			scope: itemGrid
		}, {
			hidden: this.tbarMask.charAt(0) != '1',
			xtype: 'tbseparator'
		}, {
			xtype: 'tbardelbtn',
			hidden: this.tbarMask.charAt(0) != '1',
			handler: cmdDeleteEntity,
			scope: itemGrid
		}, {
			hidden: this.tbarMask.charAt(0) != '1',
			xtype: 'tbseparator'
		}, {
			xtype: 'tbbutton',
			minWidth: 80,
			ref: '../btnToApprove',
			text: '提交审批',
			cls: 'x-btn-text-icon',
			hidden: this.tbarMask.charAt(0) != '1',
			icon: '/Content/icons/key_go.png',
			handler: cmdToApproveEntity,
			scope: itemGrid
		}, {
			hidden: this.tbarMask.charAt(0) != '1',
			xtype: 'tbseparator'
		}, {
			xtype: 'tbbutton',
			minWidth: 80,
			ref: '../btnSendOut',
			text: '提车',
			cls: 'x-btn-text-icon',
			hidden: this.tbarMask.charAt(1) != '1',
			icon: '/Content/icons/lorry_go.png',
			handler: cmdSendOut,
			scope: itemGrid
		}, {
			hidden: this.tbarMask.charAt(1) != '1',
			xtype: 'tbseparator'
		}, {
			xtype: 'tbbutton',
			minWidth: 80,
			ref: '../btnSendRecive',
			text: '接收',
			cls: 'x-btn-text-icon',
			hidden: this.tbarMask.charAt(3) != '1',
			icon: '/Content/icons/lorry_link.png',
			handler: cmdSendRecive,
			scope: itemGrid
		}, {
			hidden: this.tbarMask.charAt(3) != '1',
			xtype: 'tbseparator'
		}, {
			xtype: 'tbbutton',
			minWidth: 80,
			ref: '../btnSendStoreIn',
			text: '入库',
			cls: 'x-btn-text-icon',
			hidden: this.tbarMask.charAt(4) != '1',
			icon: '/Content/icons/lorry_add.png',
			handler: cmdSendStoreIn,
			scope: itemGrid
		}, {
			hidden: this.tbarMask.charAt(4) != '1',
			xtype: 'tbseparator'
		}, {
			xtype: "tbbutton",
			minWidth: 80,
			text: "双击查看",
			cls: "x-btn-text-icon",
			icon: "/Content/icons/pencil.png",
			disabled: true
		}, '-'];

		Ext.apply(this, {
			plugins: [gridFilter],
			sm: selModel,
			cm: gridColumn,
			tbar: toolBar,
			bbar: pagebBar,
			listeners: {
				'rowdblclick': this.onLoadEntity
			}
		});

		FsCarInfo.FsCartransfer.GridPanel.superclass.initComponent.call(this);
	},

	/****************** 
	* user function 
	******************/

	// 添加
	onAddEntity: function () {
		var itemGrid = this;
		var itemEditForm = new FsCarInfo.FsCartransfer.EditForm({
			//调拨类型
			transferType: this.transferType,
			listeners: {
				'afterSave': function (ele, rt) {
					if (rt) {
						ele.form.reset();
						var itemGridStore = itemGrid.store;
						itemGridStore.reload();
						JsHelper.ShowInfo('添加信息成功!');
					}
				}
			}
		});
		var itemEditWin = new FsCarInfo.FsCartransfer.EditWin({
			items: [itemEditForm]
		});
		itemEditWin.show();
	},

	// 读取信息显示
	onLoadEntity: function () {
		var itemGrid = this;
		var selRecord = this.getSelectionModel().getSelected();
		if (selRecord == null) {
			JsHelper.ShowError('请选择记录编辑..');
			return -1;
		}
		var selId = selRecord.data.Id;
		var itemEditForm = new FsCarInfo.FsCartransfer.EditForm({
			Id: selId,
			dataRecord: selRecord,
			submitUrl: this.formSubmitUrl,
			submitMsg: this.formSubmitMsg,
			transferType: this.transferType,
			waitMsg: '数据加载中...',
			listeners: {
				'afterSave': function (ele, rt) {
					if (rt) {
						itemGrid.store.reload();
						JsHelper.ShowInfo('信息更新成功!');
					}
				}
			}
		});
		var itemEditWin = new FsCarInfo.FsCartransfer.EditWin({
			items: [itemEditForm]
		});
		itemEditWin.show();
		itemEditForm.form.loadRecord(selRecord);
	},

	// 删除
	onDeleteEntity: function () {
		var itemGrid = this;
		var itemGridStore = this.store;
		JsHelper.DelConfirm(function (btn) {
			if (btn == 'yes') {
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					itemGridStore.remove(r);
				}
			}
		});
	},

	// 查询
	onQueryList: function () {
		var itemGrid = this;
		var q_query = Ext.getCmp('q_query').getValue();
		itemGrid.store.load({
			params: {
				start: 0,
				limit: ALL_PAGESIZE_SETTING,
				q_query: q_query
			}
		})
	},

	// 提交选定记录..
	tbarSubmit: function (submitUrl, confirmMsg, successMsg) {
		var itemGrid = this;
		var selRecord = this.getSelectionModel().getSelected();
		if (selRecord == null) {
			JsHelper.ShowError('未选择记录.');
			return -1;
		}
		var selId = selRecord.data.Id;
		JsHelper.Confirm(confirmMsg, function (btn) {
			if (btn == 'yes') {
				var ids = [];
				var s = itemGrid.getSelectionModel().getSelections();
				for (var i = 0, r; r = s[i]; i++) {
					ids.push(r.data.Id);
				}
				//加载进度条
				Ext.MessageBox.show({
					msg: '正在提交数据到中心服务器...',
					progressText: '保存数据...',
					width: 300,
					wait: true,
					waitConfig: { interval: 1000 }
				});
				Ext.Ajax.request({
					url: submitUrl,
					params: {
						'Ids': ids.toString()
					},
					success: function (response, opts) {
						Ext.MessageBox.hide();
						var result = Ext.util.JSON.decode(response.responseText);
						if (result.success == false) {
							JsHelper.ShowError('操作失败:' + result.msg);
						} else {
							itemGrid.store.reload();
							Ext.Msg.alert('提示,操作成功', '成功。' + successMsg);
						}
					},
					failure: function (form, action) {
						Ext.MessageBox.hide();
						JsHelper.ShowError('系统异常:' + action.result.msg);
					}
				});
			}
		});
	}
});

//FsCartransfer EditForm
FsCarInfo.FsCartransfer.EditForm = Ext.extend(Infrastructure.BaseForm, {
	submitUrl: '/FsCartransfer/SaveOrUpdate',
	submitMsg: '确定要保存吗?',
	transferType: '', //调拨类型 Transfer Exp

	initComponent: function () {
		var itemEditForm = this;
		var cmdUpdate = this.onSave;

		//Form第一列
		// 定义表单列
		var firstColumn = [{
			fieldLabel: "调拨类型",
			xtype: 'infra_dictcombo',
			filterValue: 'tftype',
			valueField: 'Code',
			hiddenName: 'TransferType'
		}, {
			fieldLabel: "经办人",
			xtype: 'infra_usercombo',
			hiddenName: 'OperUserId'
		}, {
			fieldLabel: "预计出发",
			xtype: 'datefield',
			format: 'Y-m-d H:i:s',
			value: new Date().add(Date.HOUR, 1),
			hideTrigger: true,
			name: 'ExpOutTime'
		}, {
			fieldLabel: "预计到达",
			xtype: 'datefield',
			format: 'Y-m-d H:i:s',
			value: new Date().add(Date.HOUR, 3),
			hideTrigger: true,
			name: 'ExpArvTime'
		}, {
			fieldLabel: "调入仓库",
			hidden: this.transferType == '商品车外派', //临时外派
			xtype: 'infra_deptcombo',
			hiddenName: 'InDeptId'
		}, {
			fieldLabel: "事由",
			xtype: 'infra_dictcombo',
			filterValue: 'tfrson',
			hiddenName: 'Reason'
		}, {
			fieldLabel: "申请时间",
			readOnly: true,
			hidden: this.dataRecord == null,
			hideTrigger: true,
			xtype: 'datefield',
			format: 'Y-m-d H:i:s',
			name: 'CreateTime'
		}];

		//Form第二列
		var secondColumn = [{
			fieldLabel: "调出仓库",
			width: 150,
			maxLength: 36,
			readOnly: true,
			hidden: this.dataRecord == null,
			xtype: 'textfield',
			name: 'OutDept.Name'
		}, {
			fieldLabel: "调出仓管",
			width: 150,
			maxLength: 36,
			readOnly: true,
			hidden: this.dataRecord == null,
			xtype: 'textfield',
			name: 'OutDpuser.Name'
		}, {
			fieldLabel: "实际出发",
			width: 150,
			maxLength: 50,
			readOnly: true,
			hidden: this.dataRecord == null,
			xtype: 'textfield',
			name: 'ActOutTime'
		}, {
			fieldLabel: "实际到达",
			width: 150,
			maxLength: 50,
			readOnly: true,
			hidden: this.dataRecord == null,
			xtype: 'textfield',
			name: 'ActArvTime'
		}, {
			fieldLabel: "调入仓管",
			width: 150,
			maxLength: 36,
			readOnly: true,
			hidden: this.dataRecord == null,
			xtype: 'textfield',
			name: 'InDpuser.Name'
		}, {
			fieldLabel: "状态",
			width: 150,
			readOnly: true,
			hidden: this.dataRecord == null,
			xtype: 'textfield',
			name: 'State'
		}];

		//调拨车辆清单
		var carGridPanel = new FsCarInfo.FsCartransferDetail.EditorGridPanel({
			height: 250,
			tbarMask: '1111111111111',
			transferInfo: this.dataRecord,
			transferId: this.dataRecord == null ? '' : this.dataRecord.data.Id,
			hidden: this.dataRecord == null
		});

		//Form单列
		var singleColumn = [{
			xtype: 'textarea',
			fieldLabel: '描述',
			name: 'Description',
			height: 50,
			width: 430
		}, carGridPanel];

		Ext.applyIf(this, {
			items: [{
				layout: 'column',
				// 注意 现在使用的是两列 要是三列或更多
				// 请改变下面的items
				// 并在上面定义每个列的组件集合
				items: [{
					columnWidth: .5,
					bodyStyle: 'padding:1px',
					layout: 'form',
					defaultType: 'textfield',
					defaults: {
						width: 150
					},
					items: firstColumn
				}, {
					columnWidth: .5,
					bodyStyle: 'padding:1px',
					layout: 'form',
					defaultType: 'textfield',
					items: secondColumn
				}]
			}, singleColumn],
			buttons: [{
				xtype: 'btnsubmit',
				handler: this.saveItem,
				hidden: this.submitUrl == '',
				scope: itemEditForm
			}, {
				xtype: 'btncancle',
				handler: function () {
					itemEditForm.ownerCt.destroy();
				}
			}],
			reader: new FsCarInfo.FsCartransfer.JsonReader()
		});

		carGridPanel.store.load();
		FsCarInfo.FsCartransfer.EditForm.superclass.initComponent.call(this);

		//定义保存后执行的事件
		this.addEvents('afterSave');
	}
});

//FsCartransfer DetailWin
FsCarInfo.FsCartransfer.EditWin = Ext.extend(Ext.Window, {
	title: '车辆调拨单信息',
	iconCls: 'application_form',
	width: 600,
	resizable: false,
	constrain: true,
	autoHeight: true,
	modal: true,
	closeAction: 'close',
	plain: true,
	buttonAlign: 'center',

	//constructor
	initComponent: function () {
		FsCarInfo.FsCartransfer.EditWin.superclass.initComponent.call(this);
	}
});
